package com.fudan.backend.service.impl;

import com.fudan.backend.dao.OrderDao;
import com.fudan.backend.dao.ReturnGoodsRequestDao;
import com.fudan.backend.dao.UserDao;
import com.fudan.backend.exception.RetCode;
import com.fudan.backend.pojo.Order;
import com.fudan.backend.pojo.ReturnGoodsRequest;
import com.fudan.backend.pojo.statics.AccountStatic;
import com.fudan.backend.pojo.statics.BillType;
import com.fudan.backend.pojo.statics.OrderStatus;
import com.fudan.backend.pojo.statics.RequestStatus;
import com.fudan.backend.service.AccountService;
import com.fudan.backend.service.ReturnGoodsRequestService;
import com.fudan.backend.util.Snowflake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ReturnGoodsRequestServiceImpl implements ReturnGoodsRequestService {

    @Autowired
    OrderDao orderDao;

    @Autowired
    ReturnGoodsRequestDao returnGoodsRequestDao;

    @Autowired
    Snowflake snowflake;

    @Autowired
    UserDao userDao;

    @Autowired
    AccountService accountService;


    @Override
    public RetCode addReturnGoodsRequest(ReturnGoodsRequest returnGoodsRequest) {

        RetCode retCode;
        Date date = new Date();

        returnGoodsRequest.setReturnGoodsRequestId((snowflake.nextId()).toString());
        returnGoodsRequest.setInitiateTime(date);

        String orderId = returnGoodsRequest.getOrderId();
        List<ReturnGoodsRequest> unprocessedReturnGoodsRequests = returnGoodsRequestDao.selectUnprocessedReturnGoodsRequestByOrderId(orderId);
        Order order = orderDao.selectOrderByOrderId(orderId);
        Integer orderStatus = order.getStatus();
        Double allowance = order.getAllowance();

        if(unprocessedReturnGoodsRequests.size() != 0){
            retCode = RetCode.RETURN_GOODS_REQUEST_UNPROCESSED;
            returnGoodsRequest.setProcessTime(date);
            returnGoodsRequest.setStatus(RequestStatus.NOT_APPROVED);
            returnGoodsRequest.setInfo("自动审核：该订单已经提交了退货申请，请耐心等待商家审核，勿重复提交");
        }else if(allowance != 0){
            retCode = RetCode.ORDER_IS_IN_ACTIVITY;
            returnGoodsRequest.setProcessTime(date);
            returnGoodsRequest.setStatus(RequestStatus.NOT_APPROVED);
            returnGoodsRequest.setInfo("自动审核：该订单中有商品参与了活动，不能退货");
        }else if(orderStatus != OrderStatus.SHIPPED_AND_NOT_RECEIVED && orderStatus!= OrderStatus.PAID_AND_NOT_SHIPPED){
            retCode = RetCode.ORDER_STATUS_ERROR;
            returnGoodsRequest.setProcessTime(date);
            returnGoodsRequest.setStatus(RequestStatus.NOT_APPROVED);
            returnGoodsRequest.setInfo("自动审核：该订单状态不支持退货，（温馨提示，只有待付款和待收货状态下的订单才能退货哦）");
        }else {
            retCode = RetCode.RETURN_GOODS_REQUEST_SUCCESS;
            returnGoodsRequest.setStatus(RequestStatus.APPLYING);
        }

        returnGoodsRequestDao.insertReturnGoodsRequest(returnGoodsRequest);

        return retCode;
    }

    @Override
    public PageInfo<ReturnGoodsRequest> getAllReturnGoodsRequestByUserId(int current, int pageSize, String userId) {
        PageHelper.startPage(current, pageSize);
        List<ReturnGoodsRequest> returnGoodsRequests = returnGoodsRequestDao.selectReturnGoodsRequestByUserId(userId);
        return new PageInfo<ReturnGoodsRequest>(returnGoodsRequests, 5);
    }

    @Override
    public PageInfo<ReturnGoodsRequest> getAllReturnGoodsRequestByStoreId(int current, int pageSize, String storeId) {
        PageHelper.startPage(current, pageSize);
        List<ReturnGoodsRequest> returnGoodsRequests = returnGoodsRequestDao.selectReturnGoodsRequestByStoreId(storeId);
        return new PageInfo<ReturnGoodsRequest>(returnGoodsRequests, 5);
    }

    @Override
    @Transactional
    public RetCode processReturnGoodsRequest(ReturnGoodsRequest returnGoodsRequest) {
        Date date = new Date();
        returnGoodsRequest.setProcessTime(date);

        returnGoodsRequestDao.updateReturnGoodsRequest(returnGoodsRequest);

        Integer status = returnGoodsRequest.getStatus();


        if(status == RequestStatus.APPROVED){
            String orderId = returnGoodsRequest.getOrderId();//获取订单号
            Order order = orderDao.selectOrderByOrderId(orderId);//获取订单
            order.setStatus(OrderStatus.REFUND);//修改订单状态
            orderDao.updateOrder(order);//更新订单

            //获取用户ID
            String userId = returnGoodsRequest.getUserId();
            //获取用户账号ID
            String userAccountId = userDao.selectAccountIdByUserId(userId);
            //获取订单金额
            Double payment = order.getPayment();
            //将订单金额从中间账户转到用户账户
            accountService.transfer(AccountStatic.INTERMEDIATE_ACCOUNT_ID, userAccountId,payment, BillType.RETURN_GOODS_REFUND, "退货转账");
        }
        return RetCode.RETURN_GOODS_REQUEST_SUCCESS;
    }
}
